/**
 * Created by zzy on 2017/9/25.
 */
import React, {Component} from 'react';
import {
    Text,
    View,
    TouchableOpacity,
    Image,
    StyleSheet,
    ScrollView,
    PixelRatio,
    Animated,
    WebView,
    Dimensions,
    InteractionManager,
    DeviceEventEmitter
} from 'react-native';
import ViewPager from '../../js/component/ViewPager'
import waterTiketStore from '../../js/store/WaterTiketStore'
import DataUtil from '../util/DataUtil'
import NetRequestLuo from '../util/NetRequest'
import ItemCell from '../../js/component/ItemCell'
import LoadingView from '../../js/component/LoadingView'
import addressMgrStore from '../../js/store/AddrMgrStore'
import JudgeItemCell from '../componentluo/judgeitemcell'
const {height, width} = Dimensions.get('window');
import {observable, action, computed, observe} from 'mobx' ;
import {observer} from 'mobx-react/native'
import CommonUtil from '../util/CommonUtil'
import productInfoStore from '../../js/store/ProductInfoStore'
import ProductCellH from '../componentluo/ProductCellH'
import shoppingCartStore from '../store/ShoppingCartStore'

@observer
export default class ProductInfoLuo extends Component{
    @observable loading=true;
    @observable tiketProductModel={
        name:'',
        volume:'',
        productItemModels:[{name:''}]
    };
    @observable productImage=[];
    @observable commonModels=[];
    @observable shopOtherProducts=[];
    constructor(props){
        super(props);
        this.productItemId=this.props.productItemId;
        this.shopId=this.props.shopId;
        this.navigate=this.props.navigate;
        this.state={
            shop:{
                distance:0,
                totalProductCount:0
            }
        }
    }
    render(){
        let images=[];
        for(var i=0;i<this.productImage.length;i++){
            var image={uri:this.productImage[i]};
            images.push(image);
        }
        return <View style={{backgroundColor: '#f5f5f5',flex: 1}}>
            <LoadingView
                visible={this.loading}
                color="white"
                indicatorSize="small"
                messageFontSize={12}
                message=''
            />
            <ScrollView >
                {
                    images.length==0?(null):<ViewPager images={images} imageHeight={250}/>
                }
                <View style={productDetail_style.info}>
                    <View style={productDetail_style.name}>
                        <View style={[productDetail_style.border, productDetail_style.center, {marginRight: 5}]}>
                            <Text style={productDetail_style.self}>自营</Text>
                        </View>
                        <Text style={{color:'black',fontSize:15}}>{productInfoStore.productModel.name+productInfoStore.productModel.Volume}</Text>
                    </View>
                    <Text style={{marginTop: 5}}>{}</Text>
                    <View style={{flexDirection:'row',alignItems:'center'}}>
                        <Text style={productDetail_style.price}>¥{DataUtil.f2y(productInfoStore.productModel.ActiveProductItemModel.currentPrice)}
                            <Text style={{color:'gray',marginLeft:10}}>  原价
                                <Text style={{textDecorationLine:'line-through'}}>¥{DataUtil.f2y(productInfoStore.productModel.ActiveProductItemModel.originalPrice)}</Text>
                            </Text>
                        </Text>
                        <Text>已售{productInfoStore.productModel.ActiveProductItemModel.saleMount+''}</Text>
                    </View>

                </View>
                <View style={{flexDirection:'row',backgroundColor:'white',padding:10}}>
                    <Text>促销:无
                      <Text style={{color:'black'}}></Text>
                    </Text>
                </View>
                {
                    productInfoStore.productModel.TicketProductItemId?(
                    <TouchableOpacity  activeOpacity={0.9} onPress={() => {
                        if(this.tiketProductModel.name=='')return;
                        this.navigate('TicketDetails',{productItemId:this.tiketProductModel.productItemModels[0].productItemId,shopId:this.shopId});
                    }}style={{marginTop:20}}>
                        <ItemCell name={'水票更优惠'}/>
                        <View style={{flexDirection:'row',backgroundColor:'white'}}>
                            {
                                this.tiketProductModel.productItemModels.map((model,index)=>{
                                      return <Image key={index} style={{width:width/3,height:70,justifyContent:'center',alignItems:'center'}} resizeMode={'contain'} source={require('../../asserts/ticket/ticket_package_bg.png')}>
                                          <Text style={{color:'#CFE546'}}>{model.name}</Text>
                                      </Image>
                                   }
                                )
                           }
                        </View>
                    </TouchableOpacity>
                    ):(null)
                }
                <View style={{marginTop:20}}>
                    <ItemCell name={'选择'} desc={productInfoStore.productModel.Volume} rightArrowShow={false}/>
                </View>
                <View style={{flexDirection:'row',backgroundColor:'white',padding:10,marginTop:20}}>

                    <Text>服务:</Text>
                    <Text style={{color:'black',marginLeft:5}}>24小时内送达</Text>
                </View>
                {
                    productInfoStore.productModel.ActiveProductItemModel.productCategory=='桶装水'?<View style={{flexDirection:'row',backgroundColor:'white',padding:10,marginTop:1}}>
                        <Text>押金:</Text>
                            <Text style={{color:'black',marginLeft:5,flex:1}}>水站送水时将回收同一品牌空桶，无同一品牌空桶的，水站将另收取水桶押金。退押金时凭空桶及押金条与水站直接办理。与本平台无关。</Text>
                        </View>:
                        (null)
                }

                <View style={{marginTop: 20}}>
                    <ItemCell name={'商品评价('+this.commonModels.length+')'} desc="查看更多" callback={()=>{this.navigate('CommentList',{commonModels:this.commonModels})}}/>
                    <Judge commonModels={this.commonModels}/>
                </View>
                <ShopInfo shop={this.state.shop} callback={()=>{this.navigate('WaterStation',{shopId:this.state.shop.shopId})}}/>
                <ShopOtherProducts navigate={this.navigate} produtsList={this.shopOtherProducts} shopId={this.shopId} addToShoppingCart={this.addShoppingCart.bind(this)}/>
            </ScrollView>
        </View>
    }
    componentDidMount(){
        InteractionManager.runAfterInteractions(() => {
            this.fetch();
            this._shopInfo();
            this._shopOtherProducts();
        });
    }
    componentWillUnmount(){
    };
    _shopOtherProducts(){
        let otherProductsParam={
            shopId:this.shopId,
            sortType:'desc',
            categoryType:'saleMount'
        };
        NetRequestLuo.oldproductList(otherProductsParam,'entityProduct').then((data)=>{
            LOG('商品列表----------'+JSON.stringify(data));
            this.shopOtherProducts=data.productList;
        })
    }
    _shopInfo(){
        let shopParam={
            cityName: '',
            latitude: addressMgrStore.activeAddress.latitude,
            longtitude: addressMgrStore.activeAddress.longitude,
            shopId: this.shopId
        };
        NetRequestLuo.shopInfo(shopParam).then((data)=>{
            LOG('店铺信息---------'+JSON.stringify(data));
            this.setState({
                shop:data
            })
        })
    }
    fetch(){
        this.loading=true;
        var tiketParam={
            productItemId:this.productItemId,
            shopId:this.shopId
        };
        NetRequestLuo.getTiketInfo(tiketParam).then((data)=>{
            LOG('product----------' + JSON.stringify(data));
            productInfoStore.setProductItemModels(data);
            this.productImage=data.productModel.productItemModels[0].productImage;
            this.commonModels=data.commonModels;
            this.loading=false;
            this.toWaterTiket();
        });
    }
    toWaterTiket(){
        var param={
            productItemId:productInfoStore.productModel.TicketProductItemId,
            shopId:this.shopId
        };
        NetRequestLuo.getTiketInfo(param).then((data)=>{
            LOG('tiket----------' + JSON.stringify(data));
            this.tiketProductModel=data.productModel;
        });
    }
    addShoppingCart(item){
        // this.refs.buyFooter.animateShoppingCart();
        let param={
            productItemId: item.productItemModels[0].productItemId,
            productType: item.type,
            shopId: this.shopId,
        };
        NetRequestLuo.addShoppingCart(param,'increase').then((data)=>{
            LOG('添加商品---------'+JSON.stringify(data));
            shoppingCartStore.getShoppingCart();
            DeviceEventEmitter.emit('refreshShopList');//刷新购物车
        })
    }
}
@observer
class Judge extends Component{
    render(){
        return <View>
            {
                    this.props.commonModels.map((data,index)=>{
                    if(index>=2)return;
                    return <JudgeItemCell common={data} key={index}/>
                })
            }
        </View>
    }
}

class ShopInfo extends Component{

    render(){
        let {callback}=this.props;
        let {imageUrl,name,totalProductCount,distance,score}=this.props.shop;
        return <View style={{backgroundColor:'white',padding:10,marginTop:20}}>

            <View style={{flexDirection:'row',alignItems:'center'}}>
                <Image style={{width:40,height:40,resizeMode:'contain'}} source={{uri:imageUrl}}></Image>
                <View style={{justifyContent:'center',marginLeft:5,flex:1}}>
                    <Text>{name}</Text>
                    <View style={{flexDirection:'row',marginTop:3,alignItems:'center'}}>
                        {
                           CommonUtil.getStoreStars(score)
                        }
                        <Text style={{marginLeft:3}}>{score}</Text>
                    </View>
                </View>

                <TouchableOpacity style={{marginRight:10,borderRadius:3, borderWidth: 3 / PixelRatio.get(),padding:3,borderColor: '#1EAFF3'}}
                    onPress={callback}
                >
                    <Text style={{color:'#1EAFF3'}}>进入店铺</Text>
                </TouchableOpacity>
            </View>
            <View style={{flexDirection:'row',justifyContent:'center',marginTop:20}}>
                <View style={{alignItems:'center',marginRight:100}}>
                    <Text style={{color:'black'}}>{totalProductCount+''}</Text>
                    <Text>全部商品</Text>
                </View>
                <View style={{alignItems:'center'}}>
                    <Text style={{color:'black'}}>{distance+''}</Text>
                    <Text>距离</Text>
                </View>
            </View>
        </View>
    }
}
class ShopOtherProducts extends Component{
    render(){
        let {navigate,produtsList,shopId,addToShoppingCart} = this.props;
        return <View style={{marginTop:20}}>
           <Text style={{backgroundColor:'white',padding:5}}>为你推荐</Text>
           <View style={{flexDirection:'row',flexWrap:'wrap'}}>
            {
                produtsList.map((item,i)=>{
                    return <ProductCellH key={i} item={item} addToShoppingCart={addToShoppingCart} callback={()=>{
                        navigate('ProductsDetailsLuo',{productItemId:item.productItemModels[0].productItemId,shopId:shopId});
                    }}/>
                })
            }
           </View>
        </View>
    }
}
const productDetail_style = StyleSheet.create({
    sv: {
        backgroundColor: '#f5f5f5',
        flex: 1
    },
    swiper: {
        height: 0
    },
    swiper_image: {
        height: 150,
        resizeMode: 'cover'
    },
    info: {
        padding: 10,
        backgroundColor: 'white'
    },
    border: {
        borderWidth: 1 / PixelRatio.get(),
        borderColor: 'red'
    },
    center: {
        justifyContent: 'center',
        alignItems: 'center'
    },
    self: {
        fontSize: 10,
        fontWeight: '100',
        color: 'red',
        textAlign: 'justify',
        textAlignVertical: 'center'
    },
    name: {
        flexDirection: 'row'
    },
    price: {
        color: 'red',
        marginTop: 5,
        flex:1
    },
    msg: {
        flexDirection: 'row',
        marginTop: 2,
        backgroundColor: 'white',
        padding: 10,
    },
    price_con: {
        flexDirection: 'row',
        alignItems: 'center'
    },
    right_icon: {
        width: 13,
        height: 13,
        resizeMode: 'contain'
    },
    fee_text: {},
    group: {
        marginTop: 20
    },
    group_choice: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        backgroundColor: 'white',
        padding: 10
    },
    choice_border: {
        borderWidth: 1 / PixelRatio.get(),
        borderColor: 'gray'
    },
    choice_text: {
        color: 'gray',
        textAlign: 'justify',
        textAlignVertical: 'center',
        padding: 5
    },
    detail: {
        backgroundColor: 'white',
        marginTop: 20,
        padding: 10
    },
    comment: {
        marginTop: 20,
    }

});